//
//  HTClassCalendarVC.swift
//  QuitSmokingApp
//
//  Created by   on 2024/3/6.
//

import UIKit
import FSCalendar
import BRPickerView

class HTClassCalendarVC: HTClassViewController {
    
    lazy var var_titleLabel: UILabel = {
        let var_label = UILabel()
        var_label.text = "Check-in"
        var_label.textColor = .white
        var_label.font = .systemFont(ofSize: 28.auto(), weight: .bold)
        return var_label
    }()
    
    lazy var var_totalBg: UIImageView = {
       let var_img = UIImageView()
        var_img.image = UIImage(named: "icon_total_days_bg")
        return var_img
    }()
    
    lazy var var_totalIcon: UIImageView = {
        let var_icon = UIImageView()
        var_icon.image = UIImage(named: "icon_total_days")
        return var_icon
    }()
    
    lazy var var_totalLabel: UILabel = {
        let var_total = UILabel()
        var_total.textColor = .white
        var_total.font = .systemFont(ofSize: 28.auto(), weight: .bold)
        return var_total
    }()
    
    lazy var var_statusLabel: UILabel = {
        let var_status = UILabel()
        let var_attStr = NSMutableAttributedString(string: "CHECK-IN COMPLETED")
        var_attStr.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.auto(), weight: .bold)], range: NSMakeRange(0, 1))
        var_attStr.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12.auto(), weight: .bold)], range: NSMakeRange(1, var_attStr.length - 1))
        var_status.attributedText = var_attStr
        var_status.textColor = .white
        return var_status
    }()
    
    //日历
    fileprivate weak var var_calendar: FSCalendar!
    
    lazy var var_leftBtn: UIButton = {
        let var_left = UIButton()
        var_left.setBackgroundImage(UIImage(named: "icon_rl_btn_left"), for: .normal)
        var_left.setBackgroundImage(UIImage(named: "icon_rl_btn_left"), for: [.normal, .highlighted])
        return var_left
    }()
    
    lazy var var_rightBtn: UIButton = {
        let var_right = UIButton()
        var_right.setBackgroundImage(UIImage(named: "icon_rl_btn_right"), for: .normal)
        var_right.setBackgroundImage(UIImage(named: "icon_rl_btn_right"), for: [.normal, .highlighted])
        return var_right
    }()
    
    lazy var var_middleBtn: UIButton = {
        let var_midBtn = UIButton()
        return var_midBtn
    }()
    
    lazy var var_checkBtn: UIButton = {
        let var_btn = UIButton()
        var_btn.setBackgroundImage(UIImage(named: "icon_rl_btn_bg"), for: .normal)
        var_btn.setBackgroundImage(UIImage(named: "icon_rl_btn_bg"), for: [.normal, .highlighted])
        var_btn.setTitle("CHECK-IN", for: .normal)
        var_btn.setTitleColor(.white, for: .normal)
        var_btn.titleLabel?.font = .systemFont(ofSize: 20.auto(), weight: .bold)
        return var_btn
    }()
    
    //日期格式化
    fileprivate lazy var var_dateFormatter: DateFormatter = {
        let var_formatter = DateFormatter()
        var_formatter.dateFormat = "yyyy-MM-dd"
        return var_formatter
    }()
    
    
    //是否签到
    var var_isChecked: Bool {
        get {
            return HTClassStorage.ht_getSignedinList().contains((self.var_dateFormatter.string(from: Date())))
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化UI
        ht_initWithUI()
        ht_addHandle()
        //刷新汇总view
        ht_reloadTotalView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    func ht_addHandle(){
        //点击签到
        var_checkBtn.onTap { [weak self] in
            if self?.var_isChecked == true {
                HTClassHudView().ht_showLargeToastOnView(var_view: self!.view, var_title: "Check-in for today has aready been completed.", var_iconImage: "", var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
                return
            }
            HTClassStorage.ht_signin(var_signinDate: (self?.var_dateFormatter.string(from: Date()))!)
//            HTClassStorage.ht_signin(var_signinDate: "2024-03-08")
            self?.var_calendar.reloadData()
            //刷新汇总view
            self?.ht_reloadTotalView()
            //新增积分
            HTClassStorage.ht_addIntegral(var_integral: 1)
            HTClassHudView().ht_showLargeToastOnView(var_view: self!.view, var_title: "Check-in successful!", var_iconImage: "icon_toast_success", var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
        }
        
        //上一月
        var_leftBtn.onTap { [weak self] in
            let var_currentMonth = self?.var_calendar.currentPage
            let var_previousMonth = NSCalendar.init(identifier: .gregorian)?.date(byAdding: .month, value: -1, to: var_currentMonth!)
            self?.var_calendar.setCurrentPage(var_previousMonth!, animated: true)
            self?.var_calendar.calendarHeaderView.reloadData()
            //刷新汇总view
            self?.ht_reloadTotalView()
        }
        
        //下一月
        var_rightBtn.onTap { [weak self] in
            let var_currentMonth = self?.var_calendar.currentPage
            let var_nextMonth = NSCalendar.init(identifier: .gregorian)?.date(byAdding: .month, value: 1, to: var_currentMonth!)
            self?.var_calendar.setCurrentPage(var_nextMonth!, animated: true)
            self?.var_calendar.calendarHeaderView.reloadData()
            //刷新汇总view
            self?.ht_reloadTotalView()
        }
        
        //选择日期
        var_middleBtn.onTap { [weak self] in
            let var_picker = BRDatePickerView(pickerMode: BRDatePickerMode.YM)
            var_picker.selectDate = self?.var_calendar.currentPage
            var_picker.resultBlock = { var_result, var_value in
                self?.var_calendar.currentPage = var_result!
                //刷新汇总view
                self?.ht_reloadTotalView()
            }
            let var_pickerStyle = BRPickerStyle()
            var_pickerStyle.pickerColor = UIColor("#212329")
            var_pickerStyle.pickerTextColor = UIColor("#999999")
            var_pickerStyle.selectRowTextFont = .systemFont(ofSize: 14.auto(), weight: .bold)
            var_pickerStyle.selectRowTextColor = .white
            var_pickerStyle.titleBarColor = UIColor("#58EDFF")
            var_pickerStyle.doneTextFont = .systemFont(ofSize: 14.auto(), weight: .bold)
            var_pickerStyle.doneTextColor = .black
            var_pickerStyle.cancelTextFont = .systemFont(ofSize: 14.auto(), weight: .bold)
            var_pickerStyle.cancelTextColor = .black
            var_pickerStyle.separatorColor = UIColor("#58EDFF")
            var_picker.pickerStyle = var_pickerStyle
            var_picker.show()
        }
    }
    
    // 刷新汇总view
    func ht_reloadTotalView(){
        var_totalLabel.text = "\(HTClassCalculationTool.ht_filterSignedDatesInSameMonth(var_dates: HTClassStorage.ht_getSignedinList(), var_referenceDate: var_calendar.currentPage).count) day"
        
        if HTClassCalculationTool.ht_isCurrentMonth(var_referenceDate: var_calendar.currentPage) {
            var_statusLabel.isHidden = !var_isChecked
            var_totalLabel.snp.updateConstraints { make in
                if var_isChecked {
                    make.centerY.equalToSuperview().offset(-10.auto())
                }else{
                    make.centerY.equalToSuperview()
                }
            }
        }else{
            var_statusLabel.isHidden = true
            var_totalLabel.snp.updateConstraints { make in
                make.centerY.equalToSuperview()
                
            }
        }
    }

    //初始化UI
    func ht_initWithUI() {
        self.view.addSubview(var_titleLabel)
        var_titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(HTClassTool.STATIC_statusBarHeight + 20.auto())
        }
        
        self.view.addSubview(var_totalBg)
        let var_image = UIImage(named: "icon_total_days_bg")
        let var_size = var_image!.size
        let var_height = var_size.height/var_size.width * (HTClassTool.STATIC_screenWidth - 28.auto())
        var_totalBg.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(14.auto())
            make.top.equalTo(var_titleLabel.snp.bottom).offset(20.auto())
            make.trailing.equalToSuperview().offset(-14.auto())
            make.height.equalTo(var_height)
        }
        
        var_totalBg.addSubview(var_totalLabel)
        var_totalLabel.snp.makeConstraints { make in
            make.width.greaterThanOrEqualTo(0)
            make.centerX.equalToSuperview().offset(22.auto())
            make.height.greaterThanOrEqualTo(0)
            make.centerY.equalToSuperview()
        }
        
        var_totalBg.addSubview(var_statusLabel)
        var_statusLabel.snp.makeConstraints { make in
            make.width.greaterThanOrEqualTo(0)
            make.centerX.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.top.equalTo(var_totalLabel.snp.bottom).offset(2.auto())
        }
        
        var_totalBg.addSubview(var_totalIcon)
        var_totalIcon.snp.makeConstraints { make in
            make.centerY.equalTo(var_totalLabel)
            make.size.equalTo(32.auto())
            make.trailing.equalTo(var_totalLabel.snp.leading).offset(-10.auto())
        }
        
        let var_cal = FSCalendar()
        var_cal.dataSource = self
        var_cal.delegate = self
        var_cal.backgroundColor = UIColor("#212329")
        var_cal.layer.masksToBounds = true
        var_cal.layer.cornerRadius = 8.auto()
        var_cal.layer.borderWidth = 1.auto()
        var_cal.layer.borderColor = UIColor("#298CB2").cgColor
        var_cal.calendarWeekdayView.backgroundColor = UIColor("#58EDFF")
        var_cal.allowsSelection = false
        var_cal.scrollEnabled = false
        var_cal.appearance.titleFont = .systemFont(ofSize: 14.auto(), weight: .bold)
        var_cal.appearance.titleDefaultColor = .white
        var_cal.appearance.titlePlaceholderColor = UIColor("#999999")
        var_cal.appearance.weekdayFont = .systemFont(ofSize: 14.auto(), weight: .bold)
        var_cal.appearance.weekdayTextColor = .black
        var_cal.appearance.headerTitleFont = .systemFont(ofSize: 20.auto(), weight: .bold)
        var_cal.appearance.headerTitleColor = .white
        var_cal.appearance.headerDateFormat = "yyyy.MM"
        var_cal.appearance.todayColor = .white.withAlphaComponent(0.2)
        view.addSubview(var_cal)
        var_cal.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(14.auto())
            make.trailing.equalToSuperview().offset(-14.auto())
            make.top.equalTo(var_totalBg.snp.bottom).offset(30.auto())
            make.height.equalTo(356.auto())
        }
        self.var_calendar = var_cal
        
        var_calendar.calendarHeaderView.addSubview(var_middleBtn)
        var_middleBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
            make.width.equalTo(100.auto())
        }
        
        var_calendar.calendarHeaderView.addSubview(var_leftBtn)
        var_leftBtn.snp.makeConstraints { make in
            make.trailing.equalTo(var_calendar.calendarHeaderView.snp.centerX).offset(-60.auto())
            make.size.equalTo(20.auto())
            make.centerY.equalToSuperview().offset(2.auto())
        }
        
        var_calendar.calendarHeaderView.addSubview(var_rightBtn)
        var_rightBtn.snp.makeConstraints { make in
            make.leading.equalTo(var_calendar.calendarHeaderView.snp.centerX).offset(60.auto())
            make.size.equalTo(20.auto())
            make.centerY.equalToSuperview().offset(2.auto())
        }
        
        view.addSubview(var_checkBtn)
        var_checkBtn.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(14.auto())
            make.trailing.equalToSuperview().offset(-14.auto())
            make.top.equalTo(var_calendar.snp.bottom).offset(30.auto())
            make.height.equalTo(44.auto())
        }
        
    }

}


extension HTClassCalendarVC: FSCalendarDataSource, FSCalendarDelegate, FSCalendarDelegateAppearance{
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor? {
        let key = self.var_dateFormatter.string(from: date)
        if HTClassStorage.ht_getSignedinList().contains(key) {
            return UIColor("#58EDFF").withAlphaComponent(0.1)
        }
        return nil
    }
    
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, borderDefaultColorFor date: Date) -> UIColor? {
        let key = self.var_dateFormatter.string(from: date)
        if HTClassStorage.ht_getSignedinList().contains(key) {
            return UIColor("#58EDFF")
        }
        return nil
    }
}
